package PDFd.loading;


import gen.R;
import PDFd.HomeActivity;
import PDFd.Instance.InstanceManager;
import PDFd.Instance.PersistanceException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.widget.TextView;

public class LoadingScreen extends Activity {
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loadingscreen);
		Thread t = new Thread(new Runnable() {
			public void run() {
				try {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
					}
					
					InstanceManager.getInstanceManager(LoadingScreen.this);
					Message msg = interthreadComms.obtainMessage();
					msg.arg1 = 0;;
					msg.obj = "Loading is taking a really long time.";
					interthreadComms.sendMessage(msg);
					
		            InstanceManager.getInstanceManager(LoadingScreen.this);
		            
		            msg = interthreadComms.obtainMessage();
		            msg.obj = "Done.";
		            msg.arg1 = 0;
		            interthreadComms.sendMessage(msg);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
					}
		            
		            msg = interthreadComms.obtainMessage();
		            msg.arg1 = 1;
		            interthreadComms.sendMessage(msg);
				} catch (PersistanceException e) {
					Log.e("HomeActivity",e.toString());
					Toast.makeText(LoadingScreen.this, "Unable to load saved files.", Toast.LENGTH_SHORT).show();
					finish();
				}
			}
		});
		t.start();
	}
	final Handler interthreadComms = new Handler() {
        public void handleMessage(Message msg) {
        	if(msg.arg1 == 0) {
            	((TextView)findViewById(R.id.loadingText)).setText((String)msg.obj);
        	} else if(msg.arg1 == 1) {
                Intent prefIntent = new Intent(LoadingScreen.this,HomeActivity.class);
                LoadingScreen.this.startActivity(prefIntent);
        	}
        }
    };
}
